const AdminBiz = require('../../../../store/admin_biz_config.js');
// 导入路径辅助模块，避免重复引用
const pathImport = require('../../../../helpers/path_import.js');
const { pageHelper, cacheHelper, createStoreBindings } = pathImport;

// 导入store和企业微信登录助手
const { adminStore } = require('../../../../config/store_config.js');
const { userStore } = require('../../../../config/store_config.js');
const qywxLoginHelper = require('../../../../../projects/plm/helpers/qywx_login_helper.js');

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		isVerifying: true
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		// 创建MobX绑定
		this.storeBindings = createStoreBindings(this, {
			store: adminStore,
			actions: ['adminLogin', 'adminLogout']
		});

		this.userStoreBindings = createStoreBindings(this, {
			store: userStore,
			fields: ['user', 'isAdmin'],
		});
		
		// 检查企业微信管理员权限
		await this.verifyQywxAdmin();
	},

	/**
	 * 验证企业微信管理员身份
	 */
	verifyQywxAdmin: async function() {
		try {
			// 检查是否在企业微信环境中
			const isInWecom = await qywxLoginHelper.isInWxworkEnv();
			if (!isInWecom) {
				return this.showError('请在企业微信中打开');
			}
			
			// 验证用户是否为管理员
			if (!this.data.isAdmin) {
				return this.showError('您不是管理员，无权访问');
			}
			
			// 企业微信管理员自动登录
			const result = await this.adminLogin('qywx_admin', '', this.data.user);
			if (result) {
				// 跳转到管理首页
				wx.reLaunch({
					url: pageHelper.fmtURLByPID('/pages/admin/index/home/admin_home'),
				});
			} else {
				this.showError('管理员身份验证失败');
			}
			
		} catch (error) {
			console.error('企业微信管理员验证失败', error);
			this.showError('管理员身份验证出错');
		}
	},
	
	/**
	 * 显示错误信息并返回
	 */
	showError: function(message) {
		wx.showModal({
			title: '提示',
			content: message,
			showCancel: false,
			success: () => {
				wx.reLaunch({
					url: pageHelper.fmtURLByPID('/pages/my/index/my_index'),
				});
			}
		});
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
		// 清理MobX绑定
		this.storeBindings.destroyStoreBindings();
		this.userStoreBindings.destroyStoreBindings();
	},

	bindBackTap: function (e) {
		wx.reLaunch({
			url: pageHelper.fmtURLByPID('/pages/my/index/my_index'),
		});
	}
})